import { BrowserWindow, ipcMain } from 'electron';
import path from "path";
 
 
export function printUtils(data) {
    return new Promise(async (resolvePrint, rejectPrint) => {
        const { printOption: options, resultData: dataList } = data
 
        let subMainWindow = new BrowserWindow({
            show: options.preview,
            webPreferences: {
                nodeIntegration: true,        // For electron >= 4.0.0
                contextIsolation: false,
                webSecurity: false,
            }
        });
 
        function renderPrintDocument(window, data) {
            return new Promise(async (resolve, reject) => {
                ipcMain.on('load-ok', (event, res) => {
                    //在这里可以添加打印的判断条件等......
                    setTimeout(() => {
                        resolve({ message: 'page-rendered', ...res });
                    }, 500)
                })
            })
        }
 
 
        // If the subMainWindow is closed, reset the `subMainWindow` var to null
        subMainWindow.on('closed', () => {
            subMainWindow = null;
        });
        // 加载打印的html文件
        const isPrdEnv = process.env.NODE_ENV === 'production'
        const staticPath = isPrdEnv ? './static' : '../../../static'
        const url = `${path.resolve(__dirname, `${staticPath}/print.html`)}`
        subMainWindow.loadFile(url);
 
        subMainWindow.webContents.on('did-finish-load', async (res) => {
            let data = []
            return renderPrintDocument(subMainWindow, data)
                .then(async (result:any) => {
                    // let width = Math.ceil((result.width) * 264.5833);
                    let height = Math.ceil((result.height + 60) * 264.5833);
                    console.info('height', result, height);
                    if (!options.preview) {
                        subMainWindow.webContents.print({
                            silent: options.silent,
                            margins: {
                                marginType: 'none'
                            },
                            printBackground: false,
                            deviceName: options.printerName,
                            copies: 1,
                            }, (success) => {
 
                            if (success) {
                                resolvePrint({type: 'success'})
                            }
                            subMainWindow.close();
                        })
                    }
                })
                .catch(err => console.warn(33, err))
        })
    })
 
}